#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from flask import Flask, jsonify, request, render_template, session, redirect, url_for
from flask_cors import CORS
import json
import os
import pymysql
from pymongo import MongoClient
from pymongo.errors import ConnectionFailure, OperationFailure
import bcrypt
from functools import wraps
from datetime import datetime

app = Flask(__name__)
CORS(app)

# 设置会话密钥（支持环境变量）
app.secret_key = os.getenv('SECRET_KEY', 'your-secret-key-change-this-in-production')

# 加载配置（支持环境变量覆盖）
def load_config():
    # 默认配置
    default_config = {
        "mysql": {
            "host": "localhost",
            "port": 3306,
            "username": "root",
            "password": "root",
            "database": "mongod_sys",
            "table": "mongodb_connections"
        },
        "server": {
            "host": "0.0.0.0",
            "port": 5000,
            "debug": False
        }
    }
    
    # 尝试从文件加载配置
    if os.path.exists('config.json'):
        try:
            with open('config.json', 'r') as f:
                file_config = json.load(f)
                # 合并配置
                default_config.update(file_config)
        except Exception as e:
            print(f"Warning: Failed to load config.json: {e}")
    
    # 环境变量覆盖配置
    config = {
        "mysql": {
            "host": os.getenv('MYSQL_HOST', default_config['mysql']['host']),
            "port": int(os.getenv('MYSQL_PORT', default_config['mysql']['port'])),
            "username": os.getenv('MYSQL_USER', default_config['mysql']['username']),
            "password": os.getenv('MYSQL_PASSWORD', default_config['mysql']['password']),
            "database": os.getenv('MYSQL_DATABASE', default_config['mysql']['database']),
            "table": os.getenv('MYSQL_TABLE', default_config['mysql']['table'])
        },
        "server": {
            "host": os.getenv('SERVER_HOST', default_config['server']['host']),
            "port": int(os.getenv('SERVER_PORT', default_config['server']['port'])),
            "debug": os.getenv('DEBUG', str(default_config['server']['debug'])).lower() == 'true'
        }
    }
    
    return config

config = load_config()
mongo_client = None
current_mongo_config = None

# 登录验证装饰器
def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if 'user_id' not in session:
            if request.is_json:
                return jsonify({"error": "未登录", "redirect": "/login"}), 401
            return redirect(url_for('login'))
        return f(*args, **kwargs)
    return decorated_function

# 管理员权限验证装饰器
def admin_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if 'user_id' not in session:
            if request.is_json:
                return jsonify({"error": "未登录", "redirect": "/login"}), 401
            return redirect(url_for('login'))
        
        if not session.get('is_admin', False):
            if request.is_json:
                return jsonify({"error": "需要管理员权限"}), 403
            return jsonify({"error": "需要管理员权限"}), 403
        return f(*args, **kwargs)
    return decorated_function

# 验证用户凭据
def verify_user(username, password):
    """验证用户名和密码"""
    try:
        mysql_config = config['mysql']
        connection = pymysql.connect(
            host=mysql_config['host'],
            port=mysql_config['port'],
            user=mysql_config['username'],
            password=mysql_config['password'],
            database=mysql_config['database'],
            charset='utf8mb4'
        )
        
        with connection.cursor(pymysql.cursors.DictCursor) as cursor:
            sql = "SELECT * FROM users WHERE username=%s AND is_active=1"
            cursor.execute(sql, (username,))
            user = cursor.fetchone()
            
            if user and bcrypt.checkpw(password.encode('utf-8'), user['password'].encode('utf-8')):
                # 更新最后登录时间
                update_sql = "UPDATE users SET last_login=NOW() WHERE id=%s"
                cursor.execute(update_sql, (user['id'],))
                connection.commit()
                
                return {
                    'id': user['id'],
                    'username': user['username'],
                    'email': user['email'],
                    'full_name': user['full_name'],
                    'is_admin': bool(user['is_admin'])
                }
        
        connection.close()
        return None
        
    except Exception as e:
        print(f"用户验证失败: {e}")
        return None

# 从MySQL获取MongoDB连接配置
def get_mongo_config_from_mysql():
    try:
        mysql_config = config['mysql']
        connection = pymysql.connect(
            host=mysql_config['host'],
            port=mysql_config['port'],
            user=mysql_config['username'],
            password=mysql_config['password'],
            database=mysql_config['database'],
            charset='utf8mb4'
        )
        
        with connection.cursor(pymysql.cursors.DictCursor) as cursor:
            # 查询MongoDB连接配置（假设只有一条记录，或者取第一条）
            sql = f"SELECT * FROM {mysql_config['table']} WHERE is_active=1 LIMIT 1"
            cursor.execute(sql)
            result = cursor.fetchone()
            
            if result:
                return {
                    'host': result['host'],
                    'port': result['port'],
                    'username': result['username'],
                    'password': result['password'],
                    'auth_database': result.get('auth_database', 'admin'),
                    'ssl': result.get('use_ssl', False)
                }
        
        connection.close()
        return None
        
    except Exception as e:
        print(f"从MySQL获取MongoDB配置失败: {e}")
        return None

# MongoDB连接
def get_mongo_client():
    global mongo_client, current_mongo_config
    
    # 从MySQL获取最新的MongoDB配置
    mongo_config = get_mongo_config_from_mysql()
    
    if not mongo_config:
        print("无法获取MongoDB配置")
        return None
    
    # 如果配置发生变化，重新连接
    if mongo_client is None or current_mongo_config != mongo_config:
        try:
            if mongo_client:
                mongo_client.close()
            
            connection_string = f"mongodb://{mongo_config['username']}:{mongo_config['password']}@{mongo_config['host']}:{mongo_config['port']}/{mongo_config['auth_database']}"
            mongo_client = MongoClient(connection_string)
            # 测试连接
            mongo_client.admin.command('ping')
            current_mongo_config = mongo_config
            print("MongoDB连接成功")
        except Exception as e:
            print(f"MongoDB连接失败: {e}")
            mongo_client = None
            current_mongo_config = None
    
    return mongo_client

@app.route('/health')
def health():
    """健康检查接口"""
    return jsonify({"status": "healthy", "timestamp": datetime.now().isoformat()})

@app.route('/')
@login_required
def index():
    print(f"主页访问 - Session内容: {dict(session)}")
    return render_template('index.html')

@app.route('/login')
def login():
    print(f"登录页面访问 - Session内容: {dict(session)}")
    if 'user_id' in session:
        print(f"用户已登录，重定向到主页: {session.get('username')}")
        return redirect(url_for('index'))
    print("显示登录页面")
    return render_template('login.html')

@app.route('/api/login', methods=['POST'])
def api_login():
    print(f"\n" + "="*50)
    print("🔐 用户登录请求")
    print("="*50)
    
    try:
        data = request.get_json()
        username = data.get('username', '').strip()
        password = data.get('password', '')
        
        print(f"📋 登录信息:")
        print(f"   用户名: {username}")
        print(f"   密码: {'*' * len(password)}")
        
        if not username or not password:
            print("❌ 用户名或密码为空")
            return jsonify({"error": "用户名和密码不能为空"}), 400
        
        print("🔍 验证用户凭据...")
        user = verify_user(username, password)
        
        if user:
            # 设置会话
            session['user_id'] = user['id']
            session['username'] = user['username']
            session['full_name'] = user['full_name']
            session['is_admin'] = user['is_admin']
            
            print(f"✅ 登录成功!")
            print(f"   用户ID: {user['id']}")
            print(f"   用户名: {user['username']}")
            print(f"   全名: {user['full_name']}")
            print(f"   管理员: {'是' if user['is_admin'] else '否'}")
            
            return jsonify({
                "success": True,
                "message": "登录成功",
                "user": {
                    "username": user['username'],
                    "full_name": user['full_name'],
                    "is_admin": user['is_admin']
                }
            })
        else:
            print("❌ 用户名或密码错误")
            return jsonify({"error": "用户名或密码错误"}), 401
            
    except Exception as e:
        print(f"❌ 登录过程中发生错误: {e}")
        return jsonify({"error": "登录失败，请稍后重试"}), 500
    finally:
        print("="*50)

@app.route('/api/logout', methods=['POST'])
@login_required
def api_logout():
    print(f"\n" + "="*50)
    print(f"🚪 用户登出: {session.get('username', 'Unknown')}")
    print("="*50)
    
    session.clear()
    return jsonify({"success": True, "message": "已成功登出"})

@app.route('/api/user/info', methods=['GET'])
@login_required
def get_user_info():
    return jsonify({
        "user": {
            "username": session.get('username'),
            "full_name": session.get('full_name'),
            "is_admin": session.get('is_admin', False)
        }
    })

@app.route('/api/connection/test', methods=['POST'])
@login_required
def test_connection():
    print("\n" + "="*60)
    print("🔍 开始测试当前活跃的MongoDB连接")
    print("="*60)
    
    try:
        # 获取当前活跃的连接配置
        mongo_config = get_mongo_config_from_mysql()
        
        if not mongo_config:
            print("❌ 无法获取MongoDB配置")
            return jsonify({"status": "error", "message": "无法获取MongoDB配置"}), 500
        
        print(f"📋 连接信息:")
        print(f"   主机: {mongo_config['host']}")
        print(f"   端口: {mongo_config['port']}")
        print(f"   用户名: {mongo_config['username']}")
        print(f"   密码: {'*' * len(mongo_config['password'])}")
        print(f"   认证数据库: {mongo_config['auth_database']}")
        print(f"   SSL: {'启用' if mongo_config['ssl'] else '禁用'}")
        
        connection_string = f"mongodb://{mongo_config['username']}:{mongo_config['password']}@{mongo_config['host']}:{mongo_config['port']}/{mongo_config['auth_database']}"
        print(f"🔗 连接字符串: mongodb://{mongo_config['username']}:***@{mongo_config['host']}:{mongo_config['port']}/{mongo_config['auth_database']}")
        
        print("⏳ 正在尝试连接...")
        client = get_mongo_client()
        
        if client:
            print("✅ MongoDB连接成功!")
            
            # 获取服务器信息
            try:
                server_info = client.admin.command('buildInfo')
                db_list = client.list_database_names()
                
                print(f"📊 服务器信息:")
                print(f"   MongoDB版本: {server_info.get('version', 'Unknown')}")
                print(f"   操作系统: {server_info.get('os', {}).get('name', 'Unknown')}")
                print(f"   数据库数量: {len(db_list)}")
                print(f"   数据库列表: {db_list}")
                
                return jsonify({
                    "status": "success", 
                    "message": "连接成功",
                    "server_info": {
                        "version": server_info.get('version', 'Unknown'),
                        "os": server_info.get('os', {}).get('name', 'Unknown'),
                        "databases_count": len(db_list),
                        "databases": db_list
                    }
                })
            except Exception as info_error:
                print(f"⚠️  获取服务器信息失败: {info_error}")
                return jsonify({"status": "success", "message": "连接成功，但无法获取详细信息"})
        else:
            print("❌ MongoDB连接失败")
            return jsonify({"status": "error", "message": "连接失败"}), 500
            
    except Exception as e:
        print(f"❌ 连接过程中发生错误: {e}")
        print(f"   错误类型: {type(e).__name__}")
        return jsonify({"status": "error", "message": str(e)}), 500
    finally:
        print("="*60)

def get_mongo_client_by_connection_id(connection_id):
    """根据连接ID获取MongoDB客户端"""
    try:
        mysql_config = config['mysql']
        connection = pymysql.connect(
            host=mysql_config['host'],
            port=mysql_config['port'],
            user=mysql_config['username'],
            password=mysql_config['password'],
            database=mysql_config['database'],
            charset='utf8mb4'
        )
        
        with connection.cursor(pymysql.cursors.DictCursor) as cursor:
            sql = f"SELECT * FROM {mysql_config['table']} WHERE id=%s"
            cursor.execute(sql, (connection_id,))
            result = cursor.fetchone()
            
            if not result:
                return None
            
            print(f"🔍 使用指定连接 (ID: {connection_id}): {result['name']}")
            print(f"   主机: {result['host']}:{result['port']}")
            print(f"   用户: {result['username']}")
            
            connection_string = f"mongodb://{result['username']}:{result['password']}@{result['host']}:{result['port']}/{result['auth_database']}"
            mongo_client = MongoClient(
                connection_string,
                serverSelectionTimeoutMS=10000,
                connectTimeoutMS=10000,
                socketTimeoutMS=10000,
                directConnection=True,  # 直接连接，不使用副本集发现
                retryWrites=False       # 禁用重试写入
            )
            
            # 测试连接
            mongo_client.admin.command('ping')
            print(f"✅ 连接成功!")
            
            return mongo_client
            
    except Exception as e:
        print(f"❌ 连接失败: {e}")
        return None
    finally:
        if 'connection' in locals():
            connection.close()

@app.route('/api/users/create', methods=['POST'])
@login_required
def create_user():
    print(f"\n" + "="*50)
    print("👤 创建MongoDB用户请求")
    print("="*50)
    
    try:
        data = request.get_json()
        database = data.get('database')
        username = data.get('username')
        password = data.get('password')
        roles = data.get('roles', [])
        
        # 获取查询参数
        connection_id = request.args.get('connection_id', None)
        
        print(f"📋 用户信息:")
        print(f"   目标数据库: {database}")
        print(f"   用户名: {username}")
        print(f"   密码: {'*' * len(password)}")
        print(f"   角色数量: {len(roles)}")
        print(f"   连接ID: {connection_id or '使用当前活跃连接'}")
        
        # 验证必要参数
        if not all([database, username, password]):
            print("❌ 缺少必要参数")
            return jsonify({"error": "数据库、用户名和密码不能为空"}), 400
        
        if not roles:
            print("❌ 缺少角色信息")
            return jsonify({"error": "至少需要指定一个角色"}), 400
        
        # 根据是否指定连接ID来获取客户端
        if connection_id:
            client = get_mongo_client_by_connection_id(connection_id)
        else:
            client = get_mongo_client()
            print("🔍 使用当前活跃连接")
        
        if not client:
            print("❌ 数据库连接失败")
            return jsonify({"error": "数据库连接失败"}), 500
        
        print(f"📚 连接到数据库: {database}")
        target_db = client[database]
        
        # 创建用户
        print("👤 创建用户...")
        print(f"   角色列表:")
        for role in roles:
            print(f"     - {role['role']}@{role['db']}")
        
        try:
            result = target_db.command("createUser", username, pwd=password, roles=roles)
            print(f"✅ 用户创建成功: {result}")
            
            # 如果使用的是指定连接，关闭客户端
            if connection_id and client:
                client.close()
            
            return jsonify({
                "success": True,
                "message": f"用户 '{username}' 创建成功",
                "user": {
                    "username": username,
                    "database": database,
                    "roles": roles
                }
            })
            
        except Exception as create_error:
            error_msg = str(create_error)
            print(f"❌ 用户创建失败: {error_msg}")
            
            # 如果使用的是指定连接，关闭客户端
            if connection_id and client:
                client.close()
            
            # 处理常见错误
            if "already exists" in error_msg.lower():
                return jsonify({"error": f"用户 '{username}' 已存在"}), 400
            elif "unauthorized" in error_msg.lower():
                return jsonify({"error": "权限不足，无法创建用户"}), 403
            else:
                return jsonify({"error": f"创建用户失败: {error_msg}"}), 500
    
    except Exception as e:
        print(f"❌ 创建用户过程中发生错误: {e}")
        return jsonify({"error": str(e)}), 500
    finally:
        print("="*50)

@app.route('/api/users/delete', methods=['DELETE'])
@login_required
def delete_user():
    print(f"\n" + "="*50)
    print("🗑️  删除MongoDB用户请求")
    print("="*50)
    
    try:
        data = request.get_json()
        database = data.get('database')
        username = data.get('username')
        
        # 获取查询参数
        connection_id = request.args.get('connection_id', None)
        
        print(f"📋 删除信息:")
        print(f"   目标数据库: {database}")
        print(f"   用户名: {username}")
        print(f"   连接ID: {connection_id or '使用当前活跃连接'}")
        
        # 验证必要参数
        if not all([database, username]):
            print("❌ 缺少必要参数")
            return jsonify({"error": "数据库和用户名不能为空"}), 400
        
        # 根据是否指定连接ID来获取客户端
        if connection_id:
            client = get_mongo_client_by_connection_id(connection_id)
        else:
            client = get_mongo_client()
            print("🔍 使用当前活跃连接")
        
        if not client:
            print("❌ 数据库连接失败")
            return jsonify({"error": "数据库连接失败"}), 500
        
        print(f"📚 连接到数据库: {database}")
        target_db = client[database]
        
        # 删除用户
        print(f"🗑️  删除用户: {username}")
        
        try:
            result = target_db.command("dropUser", username)
            print(f"✅ 用户删除成功: {result}")
            
            # 如果使用的是指定连接，关闭客户端
            if connection_id and client:
                client.close()
            
            return jsonify({
                "success": True,
                "message": f"用户 '{username}' 删除成功"
            })
            
        except Exception as delete_error:
            error_msg = str(delete_error)
            print(f"❌ 用户删除失败: {error_msg}")
            
            # 如果使用的是指定连接，关闭客户端
            if connection_id and client:
                client.close()
            
            # 处理常见错误
            if "not found" in error_msg.lower() or "does not exist" in error_msg.lower():
                return jsonify({"error": f"用户 '{username}' 不存在"}), 404
            elif "unauthorized" in error_msg.lower():
                return jsonify({"error": "权限不足，无法删除用户"}), 403
            else:
                return jsonify({"error": f"删除用户失败: {error_msg}"}), 500
    
    except Exception as e:
        print(f"❌ 删除用户过程中发生错误: {e}")
        return jsonify({"error": str(e)}), 500
    finally:
        print("="*50)

@app.route('/api/users', methods=['GET'])
@login_required
def get_users():
    print(f"\n" + "="*50)
    print("🔍 获取用户列表")
    print("="*50)
    
    try:
        # 获取查询参数
        database_filter = request.args.get('database', None)
        connection_id = request.args.get('connection_id', None)
        
        print(f"📋 请求参数:")
        print(f"   数据库过滤: {database_filter or '全部'}")
        print(f"   连接ID: {connection_id or '使用当前活跃连接'}")
        
        # 根据是否指定连接ID来获取客户端
        if connection_id:
            client = get_mongo_client_by_connection_id(connection_id)
        else:
            client = get_mongo_client()
            print("🔍 使用当前活跃连接")
        
        if not client:
            print("❌ 数据库连接失败")
            return jsonify({"error": "数据库连接失败"}), 500
        
        users = []
        
        if database_filter is None:
            # 如果没有指定数据库，从admin数据库获取所有用户
            print("📚 获取所有数据库的用户...")
            admin_db = client.admin
            users_info = admin_db.command("usersInfo")
            
            for user_info in users_info.get('users', []):
                user_data = {
                    "username": user_info['user'],
                    "database": user_info['db'],
                    "roles": user_info.get('roles', [])
                }
                users.append(user_data)
        else:
            # 如果指定了数据库，从该数据库查找用户
            print(f"📚 获取数据库 '{database_filter}' 的用户...")
            try:
                target_db = client[database_filter]
                users_info = target_db.command("usersInfo")
                
                for user_info in users_info.get('users', []):
                    user_data = {
                        "username": user_info['user'],
                        "database": user_info['db'],
                        "roles": user_info.get('roles', [])
                    }
                    users.append(user_data)
            except Exception as db_error:
                # 如果在指定数据库中查找失败，尝试从admin数据库查找该数据库的用户
                print(f"⚠️  在数据库 {database_filter} 中查找用户失败: {db_error}")
                print("🔄 尝试从admin数据库查找相关用户...")
                admin_db = client.admin
                users_info = admin_db.command("usersInfo")
                
                for user_info in users_info.get('users', []):
                    # 检查用户是否与指定数据库相关
                    user_has_access = False
                    
                    # 检查主数据库
                    if user_info['db'] == database_filter:
                        user_has_access = True
                    
                    # 检查角色中的数据库
                    if not user_has_access:
                        for role in user_info.get('roles', []):
                            if role.get('db') == database_filter:
                                user_has_access = True
                                break
                    
                    if user_has_access:
                        user_data = {
                            "username": user_info['user'],
                            "database": user_info['db'],
                            "roles": user_info.get('roles', [])
                        }
                        users.append(user_data)
        
        print(f"✅ 找到 {len(users)} 个用户")
        for user in users[:3]:  # 只显示前3个用户
            print(f"   - {user['username']} (数据库: {user['database']})")
        if len(users) > 3:
            print(f"   ... 还有 {len(users) - 3} 个用户")
        
        # 如果使用的是指定连接，关闭客户端
        if connection_id and client:
            client.close()
        
        return jsonify({"users": users})
    
    except Exception as e:
        print(f"❌ 获取用户列表失败: {e}")
        return jsonify({"error": str(e)}), 500
    finally:
        print("="*50)

@app.route('/api/databases', methods=['GET'])
@login_required
def get_databases():
    print(f"\n" + "="*50)
    print("🔍 获取数据库列表")
    print("="*50)
    
    try:
        # 获取查询参数
        connection_id = request.args.get('connection_id', None)
        
        print(f"📋 请求参数:")
        print(f"   连接ID: {connection_id or '使用当前活跃连接'}")
        
        # 根据是否指定连接ID来获取客户端
        if connection_id:
            client = get_mongo_client_by_connection_id(connection_id)
        else:
            client = get_mongo_client()
            print("🔍 使用当前活跃连接")
        
        if not client:
            print("❌ 数据库连接失败")
            return jsonify({"error": "数据库连接失败"}), 500
        
        # 获取所有数据库列表
        print("📚 获取数据库列表...")
        databases = client.list_database_names()
        
        print(f"✅ 找到 {len(databases)} 个数据库")
        print(f"   数据库列表: {databases}")
        
        # 如果使用的是指定连接，关闭客户端
        if connection_id and client:
            client.close()
        
        return jsonify({"databases": databases})
    
    except Exception as e:
        print(f"❌ 获取数据库列表失败: {e}")
        return jsonify({"error": str(e)}), 500
    finally:
        print("="*50)

@app.route('/api/databases/create', methods=['POST'])
@login_required
def create_database():
    print(f"\n" + "="*50)
    print("🗃️ 创建MongoDB数据库请求")
    print("="*50)
    
    try:
        data = request.get_json()
        database_name = data.get('database_name', '').strip()
        collection_name = data.get('collection_name', 'test').strip()
        
        # 获取查询参数
        connection_id = request.args.get('connection_id', None)
        
        print(f"📋 数据库信息:")
        print(f"   数据库名称: {database_name}")
        print(f"   集合名称: {collection_name}")
        print(f"   连接ID: {connection_id or '使用当前活跃连接'}")
        
        # 验证必要参数
        if not database_name:
            print("❌ 数据库名称不能为空")
            return jsonify({"error": "数据库名称不能为空"}), 400
        
        # 验证数据库名称格式
        import re
        if not re.match(r'^[a-zA-Z0-9_-]+$', database_name):
            print("❌ 数据库名称格式不正确")
            return jsonify({"error": "数据库名称只能包含字母、数字、下划线和连字符"}), 400
        
        # 根据是否指定连接ID来获取客户端
        if connection_id:
            client = get_mongo_client_by_connection_id(connection_id)
        else:
            client = get_mongo_client()
            print("🔍 使用当前活跃连接")
        
        if not client:
            print("❌ 数据库连接失败")
            return jsonify({"error": "数据库连接失败"}), 500
        
        # 检查数据库是否已存在
        existing_databases = client.list_database_names()
        if database_name in existing_databases:
            print(f"❌ 数据库 '{database_name}' 已存在")
            if connection_id and client:
                client.close()
            return jsonify({"error": f"数据库 '{database_name}' 已存在"}), 400
        
        print(f"📚 创建数据库: {database_name}")
        print(f"📄 创建集合: {collection_name}")
        
        # 在MongoDB中，数据库是在第一次写入数据时自动创建的
        # 所以我们需要创建一个集合并插入一个文档来确保数据库被创建
        target_db = client[database_name]
        collection = target_db[collection_name]
        
        # 插入一个临时文档来创建数据库和集合
        temp_doc = {
            "_temp": True,
            "created_at": datetime.now(),
            "created_by": session.get('username', 'system'),
            "message": "Database and collection created successfully"
        }
        
        try:
            result = collection.insert_one(temp_doc)
            print(f"✅ 数据库和集合创建成功")
            print(f"   插入文档ID: {result.inserted_id}")
            
            # 删除临时文档（可选）
            collection.delete_one({"_id": result.inserted_id})
            print(f"🗑️ 临时文档已删除")
            
            # 如果使用的是指定连接，关闭客户端
            if connection_id and client:
                client.close()
            
            return jsonify({
                "success": True,
                "message": f"数据库 '{database_name}' 和集合 '{collection_name}' 创建成功",
                "database": {
                    "name": database_name,
                    "collection": collection_name
                }
            })
            
        except Exception as create_error:
            error_msg = str(create_error)
            print(f"❌ 数据库创建失败: {error_msg}")
            
            # 如果使用的是指定连接，关闭客户端
            if connection_id and client:
                client.close()
            
            # 处理常见错误
            if "unauthorized" in error_msg.lower():
                return jsonify({"error": "权限不足，无法创建数据库"}), 403
            else:
                return jsonify({"error": f"创建数据库失败: {error_msg}"}), 500
    
    except Exception as e:
        print(f"❌ 创建数据库过程中发生错误: {e}")
        return jsonify({"error": str(e)}), 500
    finally:
        print("="*50)

@app.route('/api/databases/delete', methods=['DELETE'])
@login_required
def delete_database():
    print(f"\n" + "="*50)
    print("🗑️ 删除MongoDB数据库请求")
    print("="*50)
    
    try:
        data = request.get_json()
        database_name = data.get('database_name', '').strip()
        
        # 获取查询参数
        connection_id = request.args.get('connection_id', None)
        
        print(f"📋 删除信息:")
        print(f"   数据库名称: {database_name}")
        print(f"   连接ID: {connection_id or '使用当前活跃连接'}")
        
        # 验证必要参数
        if not database_name:
            print("❌ 数据库名称不能为空")
            return jsonify({"error": "数据库名称不能为空"}), 400
        
        # 防止删除系统数据库
        system_databases = ['admin', 'local', 'config']
        if database_name in system_databases:
            print(f"❌ 不能删除系统数据库: {database_name}")
            return jsonify({"error": f"不能删除系统数据库 '{database_name}'"}), 400
        
        # 根据是否指定连接ID来获取客户端
        if connection_id:
            client = get_mongo_client_by_connection_id(connection_id)
        else:
            client = get_mongo_client()
            print("🔍 使用当前活跃连接")
        
        if not client:
            print("❌ 数据库连接失败")
            return jsonify({"error": "数据库连接失败"}), 500
        
        # 检查数据库是否存在
        existing_databases = client.list_database_names()
        if database_name not in existing_databases:
            print(f"❌ 数据库 '{database_name}' 不存在")
            if connection_id and client:
                client.close()
            return jsonify({"error": f"数据库 '{database_name}' 不存在"}), 404
        
        print(f"🗑️ 删除数据库: {database_name}")
        
        try:
            # 删除数据库
            client.drop_database(database_name)
            print(f"✅ 数据库删除成功")
            
            # 如果使用的是指定连接，关闭客户端
            if connection_id and client:
                client.close()
            
            return jsonify({
                "success": True,
                "message": f"数据库 '{database_name}' 删除成功"
            })
            
        except Exception as delete_error:
            error_msg = str(delete_error)
            print(f"❌ 数据库删除失败: {error_msg}")
            
            # 如果使用的是指定连接，关闭客户端
            if connection_id and client:
                client.close()
            
            # 处理常见错误
            if "unauthorized" in error_msg.lower():
                return jsonify({"error": "权限不足，无法删除数据库"}), 403
            else:
                return jsonify({"error": f"删除数据库失败: {error_msg}"}), 500
    
    except Exception as e:
        print(f"❌ 删除数据库过程中发生错误: {e}")
        return jsonify({"error": str(e)}), 500
    finally:
        print("="*50)

@app.route('/api/databases/<database_name>/collections', methods=['GET'])
@login_required
def get_collections(database_name):
    print(f"\n" + "="*50)
    print(f"🔍 获取数据库 '{database_name}' 的集合列表")
    print("="*50)
    
    try:
        # 获取查询参数
        connection_id = request.args.get('connection_id', None)
        
        print(f"📋 请求参数:")
        print(f"   数据库名称: {database_name}")
        print(f"   连接ID: {connection_id or '使用当前活跃连接'}")
        
        # 根据是否指定连接ID来获取客户端
        if connection_id:
            client = get_mongo_client_by_connection_id(connection_id)
        else:
            client = get_mongo_client()
            print("🔍 使用当前活跃连接")
        
        if not client:
            print("❌ 数据库连接失败")
            return jsonify({"error": "数据库连接失败"}), 500
        
        # 检查数据库是否存在
        existing_databases = client.list_database_names()
        if database_name not in existing_databases:
            print(f"❌ 数据库 '{database_name}' 不存在")
            if connection_id and client:
                client.close()
            return jsonify({"error": f"数据库 '{database_name}' 不存在"}), 404
        
        # 获取集合列表
        print(f"📚 获取集合列表...")
        target_db = client[database_name]
        collections = target_db.list_collection_names()
        
        print(f"✅ 找到 {len(collections)} 个集合")
        print(f"   集合列表: {collections}")
        
        # 如果使用的是指定连接，关闭客户端
        if connection_id and client:
            client.close()
        
        return jsonify({"collections": collections})
    
    except Exception as e:
        print(f"❌ 获取集合列表失败: {e}")
        return jsonify({"error": str(e)}), 500
    finally:
        print("="*50)

@app.route('/api/databases/<database_name>/collections/create', methods=['POST'])
@login_required
def create_collection(database_name):
    print(f"\n" + "="*50)
    print(f"📄 在数据库 '{database_name}' 中创建集合")
    print("="*50)
    
    try:
        data = request.get_json()
        collection_name = data.get('collection_name', '').strip()
        
        # 获取查询参数
        connection_id = request.args.get('connection_id', None)
        
        print(f"📋 集合信息:")
        print(f"   数据库名称: {database_name}")
        print(f"   集合名称: {collection_name}")
        print(f"   连接ID: {connection_id or '使用当前活跃连接'}")
        
        # 验证必要参数
        if not collection_name:
            print("❌ 集合名称不能为空")
            return jsonify({"error": "集合名称不能为空"}), 400
        
        # 验证集合名称格式
        import re
        if not re.match(r'^[a-zA-Z0-9_.-]+$', collection_name):
            print("❌ 集合名称格式不正确")
            return jsonify({"error": "集合名称只能包含字母、数字、下划线、点和连字符"}), 400
        
        # 根据是否指定连接ID来获取客户端
        if connection_id:
            client = get_mongo_client_by_connection_id(connection_id)
        else:
            client = get_mongo_client()
            print("🔍 使用当前活跃连接")
        
        if not client:
            print("❌ 数据库连接失败")
            return jsonify({"error": "数据库连接失败"}), 500
        
        # 检查数据库是否存在
        existing_databases = client.list_database_names()
        if database_name not in existing_databases:
            print(f"❌ 数据库 '{database_name}' 不存在")
            if connection_id and client:
                client.close()
            return jsonify({"error": f"数据库 '{database_name}' 不存在"}), 404
        
        target_db = client[database_name]
        
        # 检查集合是否已存在
        existing_collections = target_db.list_collection_names()
        if collection_name in existing_collections:
            print(f"❌ 集合 '{collection_name}' 已存在")
            if connection_id and client:
                client.close()
            return jsonify({"error": f"集合 '{collection_name}' 已存在"}), 400
        
        print(f"📄 创建集合: {collection_name}")
        
        # 创建集合（通过插入一个临时文档）
        collection = target_db[collection_name]
        temp_doc = {
            "_temp": True,
            "created_at": datetime.now(),
            "created_by": session.get('username', 'system'),
            "message": "Collection created successfully"
        }
        
        try:
            result = collection.insert_one(temp_doc)
            print(f"✅ 集合创建成功")
            print(f"   插入文档ID: {result.inserted_id}")
            
            # 删除临时文档
            collection.delete_one({"_id": result.inserted_id})
            print(f"🗑️ 临时文档已删除")
            
            # 如果使用的是指定连接，关闭客户端
            if connection_id and client:
                client.close()
            
            return jsonify({
                "success": True,
                "message": f"集合 '{collection_name}' 创建成功",
                "collection": {
                    "name": collection_name,
                    "database": database_name
                }
            })
            
        except Exception as create_error:
            error_msg = str(create_error)
            print(f"❌ 集合创建失败: {error_msg}")
            
            # 如果使用的是指定连接，关闭客户端
            if connection_id and client:
                client.close()
            
            # 处理常见错误
            if "unauthorized" in error_msg.lower():
                return jsonify({"error": "权限不足，无法创建集合"}), 403
            else:
                return jsonify({"error": f"创建集合失败: {error_msg}"}), 500
    
    except Exception as e:
        print(f"❌ 创建集合过程中发生错误: {e}")
        return jsonify({"error": str(e)}), 500
    finally:
        print("="*50)

@app.route('/api/databases/<database_name>/collections/delete', methods=['DELETE'])
@login_required
def delete_collection(database_name):
    print(f"\n" + "="*50)
    print(f"🗑️ 删除数据库 '{database_name}' 中的集合")
    print("="*50)
    
    try:
        data = request.get_json()
        collection_name = data.get('collection_name', '').strip()
        
        # 获取查询参数
        connection_id = request.args.get('connection_id', None)
        
        print(f"📋 删除信息:")
        print(f"   数据库名称: {database_name}")
        print(f"   集合名称: {collection_name}")
        print(f"   连接ID: {connection_id or '使用当前活跃连接'}")
        
        # 验证必要参数
        if not collection_name:
            print("❌ 集合名称不能为空")
            return jsonify({"error": "集合名称不能为空"}), 400
        
        # 根据是否指定连接ID来获取客户端
        if connection_id:
            client = get_mongo_client_by_connection_id(connection_id)
        else:
            client = get_mongo_client()
            print("🔍 使用当前活跃连接")
        
        if not client:
            print("❌ 数据库连接失败")
            return jsonify({"error": "数据库连接失败"}), 500
        
        # 检查数据库是否存在
        existing_databases = client.list_database_names()
        if database_name not in existing_databases:
            print(f"❌ 数据库 '{database_name}' 不存在")
            if connection_id and client:
                client.close()
            return jsonify({"error": f"数据库 '{database_name}' 不存在"}), 404
        
        target_db = client[database_name]
        
        # 检查集合是否存在
        existing_collections = target_db.list_collection_names()
        if collection_name not in existing_collections:
            print(f"❌ 集合 '{collection_name}' 不存在")
            if connection_id and client:
                client.close()
            return jsonify({"error": f"集合 '{collection_name}' 不存在"}), 404
        
        print(f"🗑️ 删除集合: {collection_name}")
        
        try:
            # 删除集合
            target_db.drop_collection(collection_name)
            print(f"✅ 集合删除成功")
            
            # 如果使用的是指定连接，关闭客户端
            if connection_id and client:
                client.close()
            
            return jsonify({
                "success": True,
                "message": f"集合 '{collection_name}' 删除成功"
            })
            
        except Exception as delete_error:
            error_msg = str(delete_error)
            print(f"❌ 集合删除失败: {error_msg}")
            
            # 如果使用的是指定连接，关闭客户端
            if connection_id and client:
                client.close()
            
            # 处理常见错误
            if "unauthorized" in error_msg.lower():
                return jsonify({"error": "权限不足，无法删除集合"}), 403
            else:
                return jsonify({"error": f"删除集合失败: {error_msg}"}), 500
    
    except Exception as e:
        print(f"❌ 删除集合过程中发生错误: {e}")
        return jsonify({"error": str(e)}), 500
    finally:
        print("="*50)

@app.route('/api/mongo-connections', methods=['GET'])
def get_all_mongo_connections():
    """获取所有MongoDB连接配置"""
    try:
        mysql_config = config['mysql']
        connection = pymysql.connect(
            host=mysql_config['host'],
            port=mysql_config['port'],
            user=mysql_config['username'],
            password=mysql_config['password'],
            database=mysql_config['database'],
            charset='utf8mb4'
        )
        
        with connection.cursor(pymysql.cursors.DictCursor) as cursor:
            # 查询所有MongoDB连接配置
            sql = f"SELECT * FROM {mysql_config['table']} ORDER BY is_active DESC, created_at DESC"
            cursor.execute(sql)
            results = cursor.fetchall()
            
            connections = []
            for result in results:
                connection_data = {
                    'id': result['id'],
                    'name': result['name'],
                    'host': result['host'],
                    'port': result['port'],
                    'username': result['username'],
                    'password': '***',  # 隐藏密码
                    'auth_database': result['auth_database'],
                    'use_ssl': bool(result['use_ssl']),
                    'is_active': bool(result['is_active']),
                    'created_at': result['created_at'].strftime('%Y-%m-%d %H:%M:%S'),
                    'updated_at': result['updated_at'].strftime('%Y-%m-%d %H:%M:%S')
                }
                connections.append(connection_data)
        
        connection.close()
        return jsonify({"connections": connections})
        
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/mongo-config', methods=['GET'])
def get_mongo_config():
    """获取当前活跃的MongoDB配置"""
    try:
        mongo_config = get_mongo_config_from_mysql()
        if mongo_config:
            # 不返回密码
            safe_config = mongo_config.copy()
            safe_config['password'] = '***'
            return jsonify({"config": safe_config})
        else:
            return jsonify({"error": "无法获取MongoDB配置"}), 500
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/mongo-config', methods=['PUT'])
def update_mongo_config():
    """更新MongoDB配置"""
    try:
        data = request.get_json()
        mysql_config = config['mysql']
        
        connection = pymysql.connect(
            host=mysql_config['host'],
            port=mysql_config['port'],
            user=mysql_config['username'],
            password=mysql_config['password'],
            database=mysql_config['database'],
            charset='utf8mb4'
        )
        
        with connection.cursor() as cursor:
            sql = f"""UPDATE {mysql_config['table']} 
                     SET host=%s, port=%s, username=%s, password=%s, 
                         auth_database=%s, use_ssl=%s, updated_at=NOW()
                     WHERE is_active=1 LIMIT 1"""
            cursor.execute(sql, (
                data['host'],
                data['port'],
                data['username'],
                data['password'],
                data.get('auth_database', 'admin'),
                data.get('ssl', False)
            ))
            connection.commit()
        
        connection.close()
        
        # 重置MongoDB连接以使用新配置
        global mongo_client, current_mongo_config
        if mongo_client:
            mongo_client.close()
        mongo_client = None
        current_mongo_config = None
        
        return jsonify({"status": "success", "message": "配置更新成功"})
        
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/mongo-connections/<int:connection_id>/activate', methods=['POST'])
def activate_mongo_connection(connection_id):
    """激活指定的MongoDB连接"""
    try:
        mysql_config = config['mysql']
        connection = pymysql.connect(
            host=mysql_config['host'],
            port=mysql_config['port'],
            user=mysql_config['username'],
            password=mysql_config['password'],
            database=mysql_config['database'],
            charset='utf8mb4'
        )
        
        with connection.cursor() as cursor:
            # 先将所有连接设为非活跃
            sql = f"UPDATE {mysql_config['table']} SET is_active=0"
            cursor.execute(sql)
            
            # 激活指定连接
            sql = f"UPDATE {mysql_config['table']} SET is_active=1 WHERE id=%s"
            cursor.execute(sql, (connection_id,))
            connection.commit()
        
        connection.close()
        
        # 重置MongoDB连接以使用新配置
        global mongo_client, current_mongo_config
        if mongo_client:
            mongo_client.close()
        mongo_client = None
        current_mongo_config = None
        
        return jsonify({"status": "success", "message": "连接已切换"})
        
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/current-environment', methods=['GET'])
def get_current_environment():
    """获取当前活跃的环境信息"""
    try:
        mysql_config = config['mysql']
        connection = pymysql.connect(
            host=mysql_config['host'],
            port=mysql_config['port'],
            user=mysql_config['username'],
            password=mysql_config['password'],
            database=mysql_config['database'],
            charset='utf8mb4'
        )
        
        with connection.cursor(pymysql.cursors.DictCursor) as cursor:
            # 查询当前活跃的连接
            sql = f"SELECT * FROM {mysql_config['table']} WHERE is_active=1 LIMIT 1"
            cursor.execute(sql)
            result = cursor.fetchone()
            
            if result:
                environment_info = {
                    'id': result['id'],
                    'name': result['name'],
                    'host': result['host'],
                    'port': result['port'],
                    'username': result['username'],
                    'auth_database': result['auth_database'],
                    'use_ssl': bool(result['use_ssl'])
                }
                return jsonify({"environment": environment_info})
            else:
                return jsonify({"error": "没有找到活跃的连接"}), 404
        
        connection.close()
        
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/mongo-connections', methods=['POST'])
@login_required
def add_mongo_connection():
    """添加新的MongoDB连接"""
    print(f"\n" + "="*50)
    print("➕ 创建新的MongoDB连接")
    print("="*50)
    
    try:
        data = request.get_json()
        
        print(f"📋 连接信息:")
        print(f"   连接名称: {data.get('name')}")
        print(f"   主机地址: {data.get('host')}:{data.get('port')}")
        print(f"   用户名: {data.get('username')}")
        print(f"   认证数据库: {data.get('auth_database', 'admin')}")
        print(f"   SSL: {data.get('use_ssl', False)}")
        print(f"   设为活跃: {data.get('is_active', False)}")
        
        mysql_config = config['mysql']
        
        connection = pymysql.connect(
            host=mysql_config['host'],
            port=mysql_config['port'],
            user=mysql_config['username'],
            password=mysql_config['password'],
            database=mysql_config['database'],
            charset='utf8mb4'
        )
        
        with connection.cursor() as cursor:
            # 如果设置为活跃连接，先将其他连接设为非活跃
            if data.get('is_active', False):
                print("🔄 将其他连接设为非活跃...")
                cursor.execute(f"UPDATE {mysql_config['table']} SET is_active=0")
            
            sql = f"""INSERT INTO {mysql_config['table']} 
                     (name, host, port, username, password, auth_database, use_ssl, is_active)
                     VALUES (%s, %s, %s, %s, %s, %s, %s, %s)"""
            
            cursor.execute(sql, (
                data['name'],
                data['host'],
                data['port'],
                data['username'],
                data['password'],
                data.get('auth_database', 'admin'),
                data.get('use_ssl', False),
                data.get('is_active', False)
            ))
            
            connection.commit()
            new_id = cursor.lastrowid
            print(f"✅ 连接创建成功，ID: {new_id}")
        
        connection.close()
        
        # 如果设置为活跃连接，重置MongoDB连接
        if data.get('is_active', False):
            global mongo_client, current_mongo_config
            if mongo_client:
                mongo_client.close()
            mongo_client = None
            current_mongo_config = None
            print("🔄 已重置MongoDB连接")
        
        return jsonify({"success": True, "message": "连接添加成功"})
        
    except Exception as e:
        print(f"❌ 创建连接失败: {e}")
        return jsonify({"error": str(e)}), 500
    finally:
        print("="*50)

@app.route('/api/mongo-connections/<int:connection_id>/test', methods=['POST'])
def test_mongo_connection(connection_id):
    """测试指定的MongoDB连接"""
    print(f"\n" + "="*60)
    print(f"🔍 开始测试MongoDB连接 (ID: {connection_id})")
    print("="*60)
    
    try:
        mysql_config = config['mysql']
        print(f"📋 从MySQL获取连接配置...")
        print(f"   MySQL服务器: {mysql_config['host']}:{mysql_config['port']}")
        print(f"   数据库: {mysql_config['database']}")
        print(f"   表: {mysql_config['table']}")
        
        connection = pymysql.connect(
            host=mysql_config['host'],
            port=mysql_config['port'],
            user=mysql_config['username'],
            password=mysql_config['password'],
            database=mysql_config['database'],
            charset='utf8mb4'
        )
        
        with connection.cursor(pymysql.cursors.DictCursor) as cursor:
            # 获取指定连接的配置
            sql = f"SELECT * FROM {mysql_config['table']} WHERE id=%s"
            cursor.execute(sql, (connection_id,))
            result = cursor.fetchone()
            
            if not result:
                print(f"❌ 连接配置不存在 (ID: {connection_id})")
                return jsonify({"status": "error", "message": "连接配置不存在"}), 404
            
            print(f"✅ 找到连接配置:")
            print(f"   连接名称: {result['name']}")
            print(f"   主机: {result['host']}")
            print(f"   端口: {result['port']}")
            print(f"   用户名: {result['username']}")
            print(f"   密码: {'*' * len(result['password'])}")
            print(f"   认证数据库: {result['auth_database']}")
            print(f"   SSL: {'启用' if result['use_ssl'] else '禁用'}")
            print(f"   状态: {'活跃' if result['is_active'] else '非活跃'}")
            
            # 尝试连接MongoDB
            try:
                connection_string = f"mongodb://{result['username']}:{result['password']}@{result['host']}:{result['port']}/{result['auth_database']}"
                print(f"🔗 连接字符串: mongodb://{result['username']}:***@{result['host']}:{result['port']}/{result['auth_database']}")
                
                print("⏳ 正在尝试连接MongoDB...")
                test_client = MongoClient(
                    connection_string, 
                    serverSelectionTimeoutMS=10000,
                    connectTimeoutMS=10000,
                    socketTimeoutMS=10000,
                    directConnection=True,  # 直接连接，不使用副本集发现
                    retryWrites=False       # 禁用重试写入
                )
                
                # 测试连接
                print("📡 执行ping命令...")
                ping_result = test_client.admin.command('ping')
                print(f"   Ping结果: {ping_result}")
                
                # 获取服务器信息
                print("📊 获取服务器信息...")
                server_info = test_client.admin.command('buildInfo')
                print(f"   MongoDB版本: {server_info.get('version', 'Unknown')}")
                print(f"   操作系统: {server_info.get('os', {}).get('name', 'Unknown')}")
                
                print("📚 获取数据库列表...")
                db_list = test_client.list_database_names()
                print(f"   数据库数量: {len(db_list)}")
                print(f"   数据库列表: {db_list}")
                
                # 尝试获取用户信息
                try:
                    print("👥 获取用户信息...")
                    users_info = test_client.admin.command("usersInfo")
                    user_count = len(users_info.get('users', []))
                    print(f"   用户数量: {user_count}")
                    for user in users_info.get('users', [])[:3]:  # 只显示前3个用户
                        print(f"     - {user.get('user')} (数据库: {user.get('db')})")
                except Exception as user_error:
                    print(f"   ⚠️  获取用户信息失败: {user_error}")
                
                test_client.close()
                print("✅ MongoDB连接测试成功!")
                
                return jsonify({
                    "status": "success", 
                    "message": "连接成功",
                    "server_info": {
                        "version": server_info.get('version', 'Unknown'),
                        "os": server_info.get('os', {}).get('name', 'Unknown'),
                        "databases_count": len(db_list),
                        "databases": db_list[:5]  # 只返回前5个数据库名
                    }
                })
                
            except Exception as mongo_error:
                print(f"❌ MongoDB连接失败:")
                print(f"   错误类型: {type(mongo_error).__name__}")
                print(f"   错误信息: {str(mongo_error)}")
                
                return jsonify({
                    "status": "error", 
                    "message": f"MongoDB连接失败: {str(mongo_error)}"
                }), 500
        
        connection.close()
        
    except Exception as e:
        print(f"❌ 测试过程中发生错误:")
        print(f"   错误类型: {type(e).__name__}")
        print(f"   错误信息: {str(e)}")
        return jsonify({"status": "error", "message": str(e)}), 500
    finally:
        print("="*60)

@app.route('/api/mongo-connections/test-all', methods=['GET'])
def test_all_mongo_connections():
    """测试所有MongoDB连接的可用性"""
    print(f"\n" + "="*60)
    print("🔍 开始测试所有MongoDB连接")
    print("="*60)
    
    try:
        mysql_config = config['mysql']
        print(f"📋 从MySQL获取所有连接配置...")
        print(f"   MySQL服务器: {mysql_config['host']}:{mysql_config['port']}")
        
        connection = pymysql.connect(
            host=mysql_config['host'],
            port=mysql_config['port'],
            user=mysql_config['username'],
            password=mysql_config['password'],
            database=mysql_config['database'],
            charset='utf8mb4'
        )
        
        with connection.cursor(pymysql.cursors.DictCursor) as cursor:
            # 获取所有连接配置
            sql = f"SELECT * FROM {mysql_config['table']} ORDER BY is_active DESC, created_at DESC"
            cursor.execute(sql)
            results = cursor.fetchall()
            
            print(f"📊 找到 {len(results)} 个连接配置")
            
            connections_status = []
            success_count = 0
            
            for i, result in enumerate(results, 1):
                print(f"\n🔍 测试连接 {i}/{len(results)}: {result['name']}")
                print(f"   主机: {result['host']}:{result['port']}")
                print(f"   用户: {result['username']}")
                print(f"   状态: {'活跃' if result['is_active'] else '非活跃'}")
                
                connection_info = {
                    'id': result['id'],
                    'name': result['name'],
                    'host': result['host'],
                    'port': result['port'],
                    'username': result['username'],
                    'auth_database': result['auth_database'],
                    'use_ssl': bool(result['use_ssl']),
                    'is_active': bool(result['is_active']),
                    'status': 'unknown',
                    'message': '',
                    'server_info': None
                }
                
                # 测试连接
                try:
                    connection_string = f"mongodb://{result['username']}:{result['password']}@{result['host']}:{result['port']}/{result['auth_database']}"
                    print(f"   🔗 连接字符串: mongodb://{result['username']}:***@{result['host']}:{result['port']}/{result['auth_database']}")
                    
                    test_client = MongoClient(connection_string, serverSelectionTimeoutMS=5000)
                    
                    # 测试连接
                    test_client.admin.command('ping')
                    
                    # 获取服务器信息
                    server_info = test_client.admin.command('buildInfo')
                    db_list = test_client.list_database_names()
                    
                    connection_info['status'] = 'success'
                    connection_info['message'] = '连接成功'
                    connection_info['server_info'] = {
                        'version': server_info.get('version', 'Unknown'),
                        'databases_count': len(db_list)
                    }
                    
                    print(f"   ✅ 连接成功! MongoDB {server_info.get('version', 'Unknown')} ({len(db_list)} 个数据库)")
                    success_count += 1
                    
                    test_client.close()
                    
                except Exception as mongo_error:
                    connection_info['status'] = 'error'
                    connection_info['message'] = f'连接失败: {str(mongo_error)}'
                    print(f"   ❌ 连接失败: {str(mongo_error)}")
                
                connections_status.append(connection_info)
        
        connection.close()
        
        print(f"\n📊 测试完成统计:")
        print(f"   总连接数: {len(results)}")
        print(f"   成功连接: {success_count}")
        print(f"   失败连接: {len(results) - success_count}")
        print(f"   成功率: {(success_count/len(results)*100):.1f}%" if results else "0%")
        
        return jsonify({"connections": connections_status})
        
    except Exception as e:
        print(f"❌ 测试过程中发生错误: {e}")
        return jsonify({"error": str(e)}), 500
    finally:
        print("="*60)

@app.route('/api/mongo-connections/<int:connection_id>', methods=['GET'])
@login_required
def get_mongo_connection(connection_id):
    """获取单个MongoDB连接配置"""
    print(f"\n" + "="*50)
    print(f"🔍 获取连接配置 ID: {connection_id}")
    print("="*50)
    
    try:
        mysql_config = config['mysql']
        connection = pymysql.connect(
            host=mysql_config['host'],
            port=mysql_config['port'],
            user=mysql_config['username'],
            password=mysql_config['password'],
            database=mysql_config['database'],
            charset='utf8mb4'
        )
        
        with connection.cursor(pymysql.cursors.DictCursor) as cursor:
            sql = f"SELECT * FROM {mysql_config['table']} WHERE id=%s"
            cursor.execute(sql, (connection_id,))
            result = cursor.fetchone()
            
            if result:
                connection_data = {
                    'id': result['id'],
                    'name': result['name'],
                    'host': result['host'],
                    'port': result['port'],
                    'username': result['username'],
                    'password': result['password'],  # 编辑时需要显示密码
                    'auth_database': result['auth_database'],
                    'use_ssl': bool(result['use_ssl']),
                    'is_active': bool(result['is_active']),
                    'created_at': result['created_at'].strftime('%Y-%m-%d %H:%M:%S'),
                    'updated_at': result['updated_at'].strftime('%Y-%m-%d %H:%M:%S')
                }
                
                print(f"✅ 找到连接配置: {result['name']}")
                connection.close()
                return jsonify({"connection": connection_data})
            else:
                print(f"❌ 连接配置不存在")
                connection.close()
                return jsonify({"error": "连接配置不存在"}), 404
        
    except Exception as e:
        print(f"❌ 获取连接配置失败: {e}")
        return jsonify({"error": str(e)}), 500
    finally:
        print("="*50)

@app.route('/api/mongo-connections/<int:connection_id>', methods=['PUT'])
@login_required
def update_mongo_connection(connection_id):
    """更新MongoDB连接配置"""
    print(f"\n" + "="*50)
    print(f"✏️ 更新连接配置 ID: {connection_id}")
    print("="*50)
    
    try:
        data = request.get_json()
        
        print(f"📋 更新数据:")
        print(f"   连接名称: {data.get('name')}")
        print(f"   主机地址: {data.get('host')}:{data.get('port')}")
        print(f"   用户名: {data.get('username')}")
        print(f"   认证数据库: {data.get('auth_database')}")
        print(f"   SSL: {data.get('use_ssl')}")
        print(f"   设为活跃: {data.get('is_active')}")
        
        mysql_config = config['mysql']
        connection = pymysql.connect(
            host=mysql_config['host'],
            port=mysql_config['port'],
            user=mysql_config['username'],
            password=mysql_config['password'],
            database=mysql_config['database'],
            charset='utf8mb4'
        )
        
        with connection.cursor() as cursor:
            # 如果设置为活跃连接，先将其他连接设为非活跃
            if data.get('is_active', False):
                print("🔄 将其他连接设为非活跃...")
                cursor.execute(f"UPDATE {mysql_config['table']} SET is_active=0")
            
            # 更新连接配置
            sql = f"""UPDATE {mysql_config['table']} 
                     SET name=%s, host=%s, port=%s, username=%s, password=%s, 
                         auth_database=%s, use_ssl=%s, is_active=%s, updated_at=NOW()
                     WHERE id=%s"""
            
            cursor.execute(sql, (
                data['name'],
                data['host'],
                data['port'],
                data['username'],
                data['password'],
                data.get('auth_database', 'admin'),
                data.get('use_ssl', False),
                data.get('is_active', False),
                connection_id
            ))
            
            if cursor.rowcount == 0:
                print(f"❌ 连接配置不存在")
                connection.close()
                return jsonify({"error": "连接配置不存在"}), 404
            
            connection.commit()
        
        connection.close()
        
        # 如果更新了活跃连接，重置MongoDB连接
        if data.get('is_active', False):
            global mongo_client, current_mongo_config
            if mongo_client:
                mongo_client.close()
            mongo_client = None
            current_mongo_config = None
            print("🔄 已重置MongoDB连接")
        
        print(f"✅ 连接配置更新成功")
        return jsonify({"success": True, "message": "连接配置更新成功"})
        
    except Exception as e:
        print(f"❌ 更新连接配置失败: {e}")
        return jsonify({"error": str(e)}), 500
    finally:
        print("="*50)

@app.route('/api/mongo-connections/<int:connection_id>', methods=['DELETE'])
@login_required
def delete_mongo_connection(connection_id):
    """删除MongoDB连接配置"""
    print(f"\n" + "="*50)
    print(f"🗑️ 删除连接配置 ID: {connection_id}")
    print("="*50)
    
    try:
        mysql_config = config['mysql']
        connection = pymysql.connect(
            host=mysql_config['host'],
            port=mysql_config['port'],
            user=mysql_config['username'],
            password=mysql_config['password'],
            database=mysql_config['database'],
            charset='utf8mb4'
        )
        
        with connection.cursor(pymysql.cursors.DictCursor) as cursor:
            # 先检查连接是否存在和是否为活跃连接
            cursor.execute(f"SELECT * FROM {mysql_config['table']} WHERE id=%s", (connection_id,))
            result = cursor.fetchone()
            
            if not result:
                print(f"❌ 连接配置不存在")
                connection.close()
                return jsonify({"error": "连接配置不存在"}), 404
            
            if result['is_active']:
                print(f"❌ 不能删除活跃连接")
                connection.close()
                return jsonify({"error": "不能删除当前活跃的连接"}), 400
            
            print(f"📋 删除连接: {result['name']}")
            print(f"   主机: {result['host']}:{result['port']}")
            
            # 删除连接配置
            cursor.execute(f"DELETE FROM {mysql_config['table']} WHERE id=%s", (connection_id,))
            connection.commit()
        
        connection.close()
        
        print(f"✅ 连接配置删除成功")
        return jsonify({"success": True, "message": "连接配置删除成功"})
        
    except Exception as e:
        print(f"❌ 删除连接配置失败: {e}")
        return jsonify({"error": str(e)}), 500
    finally:
        print("="*50)

@app.route('/api/users/<username>/roles', methods=['GET'])
@login_required
def get_user_roles(username):
    print(f"\n" + "="*50)
    print(f"🔍 获取用户 '{username}' 的角色信息")
    print("="*50)
    
    try:
        # 获取查询参数
        database = request.args.get('database', '')
        connection_id = request.args.get('connection_id', None)
        
        print(f"📋 请求参数:")
        print(f"   用户名: {username}")
        print(f"   数据库: {database}")
        print(f"   连接ID: {connection_id or '使用当前活跃连接'}")
        
        # 根据是否指定连接ID来获取客户端
        if connection_id:
            client = get_mongo_client_by_connection_id(connection_id)
        else:
            client = get_mongo_client()
            print("🔍 使用当前活跃连接")
        
        if not client:
            print("❌ 数据库连接失败")
            return jsonify({"error": "数据库连接失败"}), 500
        
        print(f"👤 获取用户角色信息...")
        
        try:
            # 从指定数据库获取用户信息
            if database:
                target_db = client[database]
                user_info = target_db.command("usersInfo", username)
            else:
                # 从admin数据库获取用户信息
                admin_db = client.admin
                user_info = admin_db.command("usersInfo", f"{username}@{database}" if database else username)
            
            users = user_info.get('users', [])
            if not users:
                print(f"❌ 用户 '{username}' 不存在")
                if connection_id and client:
                    client.close()
                return jsonify({"error": f"用户 '{username}' 不存在"}), 404
            
            user_data = users[0]
            roles = user_data.get('roles', [])
            
            print(f"✅ 找到用户角色: {len(roles)} 个")
            for role in roles:
                print(f"   - {role.get('role', 'Unknown')}@{role.get('db', 'Unknown')}")
            
            # 如果使用的是指定连接，关闭客户端
            if connection_id and client:
                client.close()
            
            return jsonify({"roles": roles})
            
        except Exception as get_error:
            error_msg = str(get_error)
            print(f"❌ 获取用户角色失败: {error_msg}")
            
            # 如果使用的是指定连接，关闭客户端
            if connection_id and client:
                client.close()
            
            if "not found" in error_msg.lower() or "does not exist" in error_msg.lower():
                return jsonify({"error": f"用户 '{username}' 不存在"}), 404
            elif "unauthorized" in error_msg.lower():
                return jsonify({"error": "权限不足，无法获取用户信息"}), 403
            else:
                return jsonify({"error": f"获取用户角色失败: {error_msg}"}), 500
    
    except Exception as e:
        print(f"❌ 获取用户角色过程中发生错误: {e}")
        return jsonify({"error": str(e)}), 500
    finally:
        print("="*50)

@app.route('/api/users/<username>/update', methods=['PUT'])
@login_required
def update_user(username):
    print(f"\n" + "="*50)
    print(f"✏️ 更新用户 '{username}' 信息")
    print("="*50)
    
    try:
        data = request.get_json()
        database = data.get('database')
        password = data.get('password', None)  # 可选的新密码
        roles = data.get('roles', [])
        
        # 获取查询参数
        connection_id = request.args.get('connection_id', None)
        
        print(f"📋 更新信息:")
        print(f"   用户名: {username}")
        print(f"   数据库: {database}")
        print(f"   更新密码: {'是' if password else '否'}")
        print(f"   角色数量: {len(roles)}")
        print(f"   连接ID: {connection_id or '使用当前活跃连接'}")
        
        # 验证必要参数
        if not all([database, username]):
            print("❌ 缺少必要参数")
            return jsonify({"error": "数据库和用户名不能为空"}), 400
        
        if not roles:
            print("❌ 缺少角色信息")
            return jsonify({"error": "至少需要指定一个角色"}), 400
        
        # 根据是否指定连接ID来获取客户端
        if connection_id:
            client = get_mongo_client_by_connection_id(connection_id)
        else:
            client = get_mongo_client()
            print("🔍 使用当前活跃连接")
        
        if not client:
            print("❌ 数据库连接失败")
            return jsonify({"error": "数据库连接失败"}), 500
        
        print(f"📚 连接到数据库: {database}")
        target_db = client[database]
        
        print(f"✏️ 更新用户信息...")
        print(f"   新角色列表:")
        for role in roles:
            print(f"     - {role['role']}@{role['db']}")
        
        try:
            # 构建更新命令
            update_command = {
                "updateUser": username,
                "roles": roles
            }
            
            # 如果提供了新密码，添加到更新命令中
            if password:
                update_command["pwd"] = password
                print("   🔐 同时更新密码")
            
            result = target_db.command(update_command)
            print(f"✅ 用户更新成功: {result}")
            
            # 如果使用的是指定连接，关闭客户端
            if connection_id and client:
                client.close()
            
            return jsonify({
                "success": True,
                "message": f"用户 '{username}' 更新成功",
                "user": {
                    "username": username,
                    "database": database,
                    "roles": roles,
                    "password_updated": bool(password)
                }
            })
            
        except Exception as update_error:
            error_msg = str(update_error)
            print(f"❌ 用户更新失败: {error_msg}")
            
            # 如果使用的是指定连接，关闭客户端
            if connection_id and client:
                client.close()
            
            # 处理常见错误
            if "not found" in error_msg.lower() or "does not exist" in error_msg.lower():
                return jsonify({"error": f"用户 '{username}' 不存在"}), 404
            elif "unauthorized" in error_msg.lower():
                return jsonify({"error": "权限不足，无法更新用户"}), 403
            else:
                return jsonify({"error": f"更新用户失败: {error_msg}"}), 500
    
    except Exception as e:
        print(f"❌ 更新用户过程中发生错误: {e}")
        return jsonify({"error": str(e)}), 500
    finally:
        print("="*50)

# ==================== 用户管理API ====================

@app.route('/api/system-users', methods=['GET'])
@login_required
def get_system_users():
    """获取系统用户列表（管理员可查看所有用户，普通用户只能查看自己）"""
    try:
        mysql_config = config['mysql']
        connection = pymysql.connect(
            host=mysql_config['host'],
            port=mysql_config['port'],
            user=mysql_config['username'],
            password=mysql_config['password'],
            database=mysql_config['database'],
            charset='utf8mb4'
        )
        
        with connection.cursor(pymysql.cursors.DictCursor) as cursor:
            if session.get('is_admin', False):
                # 管理员可以查看所有用户
                sql = """
                SELECT id, username, email, full_name, is_active, is_admin, 
                       last_login, created_at, updated_at 
                FROM users 
                ORDER BY created_at DESC
                """
                cursor.execute(sql)
            else:
                # 普通用户只能查看自己的信息
                sql = """
                SELECT id, username, email, full_name, is_active, is_admin, 
                       last_login, created_at, updated_at 
                FROM users 
                WHERE id = %s
                """
                cursor.execute(sql, (session['user_id'],))
            
            users = cursor.fetchall()
            
            # 转换时间格式
            for user in users:
                if user['last_login']:
                    user['last_login'] = user['last_login'].strftime('%Y-%m-%d %H:%M:%S')
                user['created_at'] = user['created_at'].strftime('%Y-%m-%d %H:%M:%S')
                user['updated_at'] = user['updated_at'].strftime('%Y-%m-%d %H:%M:%S')
        
        connection.close()
        return jsonify({"success": True, "users": users})
        
    except Exception as e:
        print(f"获取用户列表失败: {e}")
        return jsonify({"error": str(e)}), 500

@app.route('/api/users/change-password', methods=['POST'])
@login_required
def change_password():
    """修改当前用户密码"""
    try:
        data = request.get_json()
        current_password = data.get('current_password')
        new_password = data.get('new_password')
        confirm_password = data.get('confirm_password')
        
        if not all([current_password, new_password, confirm_password]):
            return jsonify({"error": "所有字段都是必填的"}), 400
        
        if new_password != confirm_password:
            return jsonify({"error": "新密码和确认密码不匹配"}), 400
        
        if len(new_password) < 6:
            return jsonify({"error": "密码长度至少6位"}), 400
        
        mysql_config = config['mysql']
        connection = pymysql.connect(
            host=mysql_config['host'],
            port=mysql_config['port'],
            user=mysql_config['username'],
            password=mysql_config['password'],
            database=mysql_config['database'],
            charset='utf8mb4'
        )
        
        with connection.cursor(pymysql.cursors.DictCursor) as cursor:
            # 验证当前密码
            sql = "SELECT password FROM users WHERE id = %s"
            cursor.execute(sql, (session['user_id'],))
            user = cursor.fetchone()
            
            if not user or not bcrypt.checkpw(current_password.encode('utf-8'), user['password'].encode('utf-8')):
                return jsonify({"error": "当前密码不正确"}), 400
            
            # 更新密码
            hashed_password = bcrypt.hashpw(new_password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
            update_sql = "UPDATE users SET password = %s, updated_at = NOW() WHERE id = %s"
            cursor.execute(update_sql, (hashed_password, session['user_id']))
            connection.commit()
        
        connection.close()
        return jsonify({"success": True, "message": "密码修改成功"})
        
    except Exception as e:
        print(f"修改密码失败: {e}")
        return jsonify({"error": str(e)}), 500

@app.route('/api/system-users/create', methods=['POST'])
@admin_required
def create_system_user():
    """创建系统用户（仅管理员）"""
    try:
        data = request.get_json()
        username = data.get('username')
        password = data.get('password')
        email = data.get('email')
        full_name = data.get('full_name')
        is_admin = data.get('is_admin', False)
        
        if not all([username, password]):
            return jsonify({"error": "用户名和密码是必填的"}), 400
        
        if len(password) < 6:
            return jsonify({"error": "密码长度至少6位"}), 400
        
        mysql_config = config['mysql']
        connection = pymysql.connect(
            host=mysql_config['host'],
            port=mysql_config['port'],
            user=mysql_config['username'],
            password=mysql_config['password'],
            database=mysql_config['database'],
            charset='utf8mb4'
        )
        
        with connection.cursor(pymysql.cursors.DictCursor) as cursor:
            # 检查用户名是否已存在
            check_sql = "SELECT id FROM users WHERE username = %s"
            cursor.execute(check_sql, (username,))
            if cursor.fetchone():
                return jsonify({"error": "用户名已存在"}), 400
            
            # 创建用户
            hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
            insert_sql = """
            INSERT INTO users (username, password, email, full_name, is_admin) 
            VALUES (%s, %s, %s, %s, %s)
            """
            cursor.execute(insert_sql, (username, hashed_password, email, full_name, is_admin))
            connection.commit()
        
        connection.close()
        return jsonify({"success": True, "message": "用户创建成功"})
        
    except Exception as e:
        print(f"创建用户失败: {e}")
        return jsonify({"error": str(e)}), 500

@app.route('/api/users/<int:user_id>/update', methods=['POST'])
@admin_required
def update_system_user(user_id):
    """更新系统用户信息（仅管理员）"""
    try:
        data = request.get_json()
        email = data.get('email')
        full_name = data.get('full_name')
        is_active = data.get('is_active')
        is_admin = data.get('is_admin')
        new_password = data.get('new_password')
        
        mysql_config = config['mysql']
        connection = pymysql.connect(
            host=mysql_config['host'],
            port=mysql_config['port'],
            user=mysql_config['username'],
            password=mysql_config['password'],
            database=mysql_config['database'],
            charset='utf8mb4'
        )
        
        with connection.cursor(pymysql.cursors.DictCursor) as cursor:
            # 检查用户是否存在
            check_sql = "SELECT id FROM users WHERE id = %s"
            cursor.execute(check_sql, (user_id,))
            if not cursor.fetchone():
                return jsonify({"error": "用户不存在"}), 404
            
            # 构建更新SQL
            update_fields = []
            update_values = []
            
            if email is not None:
                update_fields.append("email = %s")
                update_values.append(email)
            
            if full_name is not None:
                update_fields.append("full_name = %s")
                update_values.append(full_name)
            
            if is_active is not None:
                update_fields.append("is_active = %s")
                update_values.append(is_active)
            
            if is_admin is not None:
                update_fields.append("is_admin = %s")
                update_values.append(is_admin)
            
            if new_password:
                if len(new_password) < 6:
                    return jsonify({"error": "密码长度至少6位"}), 400
                hashed_password = bcrypt.hashpw(new_password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
                update_fields.append("password = %s")
                update_values.append(hashed_password)
            
            if update_fields:
                update_fields.append("updated_at = NOW()")
                update_values.append(user_id)
                
                update_sql = f"UPDATE users SET {', '.join(update_fields)} WHERE id = %s"
                cursor.execute(update_sql, update_values)
                connection.commit()
        
        connection.close()
        return jsonify({"success": True, "message": "用户信息更新成功"})
        
    except Exception as e:
        print(f"更新用户失败: {e}")
        return jsonify({"error": str(e)}), 500

@app.route('/api/users/<int:user_id>/delete', methods=['POST'])
@admin_required
def delete_system_user(user_id):
    """删除系统用户（仅管理员）"""
    try:
        # 不能删除自己
        if user_id == session['user_id']:
            return jsonify({"error": "不能删除自己的账号"}), 400
        
        mysql_config = config['mysql']
        connection = pymysql.connect(
            host=mysql_config['host'],
            port=mysql_config['port'],
            user=mysql_config['username'],
            password=mysql_config['password'],
            database=mysql_config['database'],
            charset='utf8mb4'
        )
        
        with connection.cursor(pymysql.cursors.DictCursor) as cursor:
            # 检查用户是否存在
            check_sql = "SELECT username FROM users WHERE id = %s"
            cursor.execute(check_sql, (user_id,))
            user = cursor.fetchone()
            
            if not user:
                return jsonify({"error": "用户不存在"}), 404
            
            # 删除用户
            delete_sql = "DELETE FROM users WHERE id = %s"
            cursor.execute(delete_sql, (user_id,))
            connection.commit()
        
        connection.close()
        return jsonify({"success": True, "message": f"用户 {user['username']} 删除成功"})
        
    except Exception as e:
        print(f"删除用户失败: {e}")
        return jsonify({"error": str(e)}), 500

@app.route('/api/user-info', methods=['GET'])
@login_required
def get_current_user_info():
    """获取当前用户信息"""
    try:
        mysql_config = config['mysql']
        connection = pymysql.connect(
            host=mysql_config['host'],
            port=mysql_config['port'],
            user=mysql_config['username'],
            password=mysql_config['password'],
            database=mysql_config['database'],
            charset='utf8mb4'
        )
        
        with connection.cursor(pymysql.cursors.DictCursor) as cursor:
            sql = """
            SELECT id, username, email, full_name, is_active, is_admin, 
                   last_login, created_at, updated_at 
            FROM users 
            WHERE id = %s
            """
            cursor.execute(sql, (session['user_id'],))
            user = cursor.fetchone()
            
            if user:
                # 转换时间格式
                if user['last_login']:
                    user['last_login'] = user['last_login'].strftime('%Y-%m-%d %H:%M:%S')
                user['created_at'] = user['created_at'].strftime('%Y-%m-%d %H:%M:%S')
                user['updated_at'] = user['updated_at'].strftime('%Y-%m-%d %H:%M:%S')
        
        connection.close()
        return jsonify({"success": True, "user": user})
        
    except Exception as e:
        print(f"获取用户信息失败: {e}")
        return jsonify({"error": str(e)}), 500

@app.route('/api/users/profile', methods=['POST'])
@login_required
def update_profile():
    """更新当前用户的个人信息"""
    try:
        data = request.get_json()
        email = data.get('email')
        full_name = data.get('full_name')
        
        mysql_config = config['mysql']
        connection = pymysql.connect(
            host=mysql_config['host'],
            port=mysql_config['port'],
            user=mysql_config['username'],
            password=mysql_config['password'],
            database=mysql_config['database'],
            charset='utf8mb4'
        )
        
        with connection.cursor(pymysql.cursors.DictCursor) as cursor:
            # 构建更新SQL
            update_fields = []
            update_values = []
            
            if email is not None:
                update_fields.append("email = %s")
                update_values.append(email)
            
            if full_name is not None:
                update_fields.append("full_name = %s")
                update_values.append(full_name)
            
            if update_fields:
                update_fields.append("updated_at = NOW()")
                update_values.append(session['user_id'])
                
                update_sql = f"UPDATE users SET {', '.join(update_fields)} WHERE id = %s"
                cursor.execute(update_sql, update_values)
                connection.commit()
        
        connection.close()
        return jsonify({"success": True, "message": "个人信息更新成功"})
        
    except Exception as e:
        print(f"更新个人信息失败: {e}")
        return jsonify({"error": str(e)}), 500

if __name__ == '__main__':
    print("正在启动Flask应用...")
    server_config = config['server']
    print(f"服务器配置: {server_config}")
    app.run(
        host=server_config['host'],
        port=server_config['port'],
        debug=server_config['debug']
    )